<?php

declare(strict_types=1);

namespace App\RoomMessageBatchSend\Logic;

use Hyperf\Di\Annotation\Inject;
use App\RoomMessageBatchSend\Service\RoomMessageBatchSendService;

class IndexLogic
{
    /**
     * @Inject
     * @var RoomMessageBatchSendService
     */
    private $roomMessageBatchSend;

    /**
     * @param array $params 请求参数
     * @return array 响应数组
     */
    public function handle(array $params): array
    {
        ## 组织查询条件
        $where = [
//            ['user_id', '=', $params['userId']],
            ['corp_id', '=', $params['corpId']]
        ];

        if (isset($params['batchTitle']) && !empty($params['batchTitle'])) {
            $where[] = ['batch_title', 'like', '%' . $params['batchTitle'] . '%'];
        }

        $options = [
            'page' => $params['page'],
            'perPage' => $params['perPage'],
            'orderByRaw' => 'id desc',
        ];

        ## 查询数据
        $res = $this->roomMessageBatchSend->getRoomMessageBatchSendList($where, ['*'], $options);

        ## 组织响应数据
        $data = [
            'current' => $params['page'],
            'size' => $params['perPage'],
            'total' => 0,
            'pages' => 0,
            'records' => [],
        ];

        if (empty($res['data']) && !is_array($res['data'])) {
            return $data;
        }
        foreach ((array)$res['data'] as $key => $val) {
            $res['data'][$key]['content'] = json_decode($val['content'], true);
            if(isset($val['content']) && is_array($val['content'])) {
                foreach ((array)$val['content'] as $k => $v) {
                    if (isset($v['local_url'])) {
                        $res['data'][$key]['content'][$k]['local_url'] = file_full_url($v['local_url']);
                    }
                }
            }
        }
        ## 处理分页数据
        $data['total'] = $res['total'];
        $data['pages'] = $res['last_page'];
        $data['records'] = $this->handleData($res['data']);

        return $data;
    }

    protected function handleData($data): array
    {
        foreach ($data as $k => $v) {
            if (!empty($v['content'])) {
                foreach ($v['content'] as $key => $content) {
                    if (!isset($content['msgType'])) {
                        continue;
                    }
                    if ($content['msgType'] === 'image') {
                        $data[$k]['content'][$key]['pic_url'] = file_full_url($content['pic_url']);
                    }
                    if ($content['msgType'] === 'link') {
                        $data[$k]['content'][$key]['pic_url'] = file_full_url($content['pic_url']);
                    }
                    if ($content['msgType'] === 'miniprogram') {
                        $data[$k]['content'][$key]['pic_url'] = file_full_url($content['pic_url']);
                    }
                }
            }
        }
        return $data;
    }
}
